package com.conn;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ConnectionUtil {
	public static Connection getConnection(String ip,String user,String pwd) {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://" + ip + ":33306/information_schema?serverTimezone=GMT%2B8&useSSL=false";
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url, user, pwd);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}	
	
	
	public static void close(ResultSet rs,PreparedStatement psts,Connection con) {
		if(null != rs) {
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(null != psts) {
			try {
				psts.close();
				psts = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(null != con) {
			try {
				con.close();
				con = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static List<Map<String,String>> select(String sql,String ip,String user,String pwd){
		Connection con = null;
		PreparedStatement psts = null;
		ResultSet rs = null;
		try {
			con = getConnection(ip,user,pwd);
			psts = con.prepareStatement(sql);
			rs = psts.executeQuery();
			
			ResultSetMetaData rmd = rs.getMetaData();
			
			List<Map<String,String>> lists = new ArrayList<Map<String,String>>();
			while(rs.next()) {
				Map<String,String> maps = new HashMap<String,String>();
				for (int i = 0; i < rmd.getColumnCount(); i++) {
					String column = rmd.getColumnName(i+1);
					maps.put(column, rs.getString(column));
				}
				
				lists.add(maps);
			}
			return lists;
		} catch (SQLException e) {
			System.out.println(sql);
			e.printStackTrace();
		} finally {
			close(rs, psts, con);
		}
		return null;
	}

}
